package labox.innovation.db;

import java.sql.ResultSet;
import java.sql.SQLException;

import labox.innovation.config.Config;
import labox.innovation.db.core.SqlData;
import labox.innovation.db.manager.DBConnetionStateManager;
import labox.innovation.db.proxy.ConnectionProxy;
import labox.innovation.db.proxy.PreparedStatementProxy;
import labox.innovation.db.util.DbUtil;
import labox.innovation.db.util.SqlDataIdFactory;
import labox.innovation.gameserver.datatables.CharNameTable;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ���ŵ���
 * 
 * @author Lian
 * 
 */
public class PropGrantDAO {
	private static Logger _log = LoggerFactory.getLogger(PropGrantDAO.class);
	/**
	 * ɾ��
	 */
	private static final String PHYSICAL_DELETE_PROPGRANT = "delete from propgrant where orderId=?";
	/**
	 * ��Ӷ���
	 */
	private static final String ADD_ORDER_PROPGRANT = "insert into propgrant (templetId,count,charId,grantTime) values(?,?,?,?)";

	/**
	 * ���ؽ�ɫ������
	 */
	private static final String SELECT_ORDER_PROPGRANT = "select * from propgrant where charId=?";

	/**
	 * ���ŵ���
	 * 
	 * @param characterId ��ɫId
	 * @param templetId ��Ʒģ��Id
	 * @param count ����
	 */
	public static void GrantProp(long characterId, int templetId, int count) {
		if (count < 0)
			return;
		Object[] params;
		ConnectionProxy con = null;
		PreparedStatementProxy ptmt = null;
		int rs = 0;
		SqlData data = null;
		StringBuilder buildder = new StringBuilder("���߷��͵���:");
		try {
			if (DBConnetionStateManager.getDbState()) {
				con = ConnectionProxy.newInstance();
				if (con != null)
					ptmt = con.prepareStatement(ADD_ORDER_PROPGRANT);
				if (!DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, ptmt)) {
					params = new Object[] { templetId, count, characterId, System.currentTimeMillis() };
					data = new SqlData(SqlDataIdFactory.createSqlId("Add_ORDER_PROPGANT", System.currentTimeMillis()), ADD_ORDER_PROPGRANT, params);
					DBConnetionStateManager.addDbTask(data);
				} else {
					ptmt.setInt(1, templetId);
					ptmt.setInt(2, count);
					ptmt.setLong(3, characterId);
					ptmt.setLong(4, System.currentTimeMillis());
					rs = ptmt.executeUpdate();
					buildder.append("(").append(templetId).append(")").append(",").append(count);
					_log.info(buildder.toString(), characterId, CharNameTable.getInstance().getNameById(characterId));
					if (rs == PreparedStatementProxy.NETWORKDISCONNECTION) {
						params = new Object[] { templetId, count, characterId, System.currentTimeMillis() };
						data = new SqlData(SqlDataIdFactory.createSqlId("Add_ORDER_PROPGANT", System.currentTimeMillis()), ADD_ORDER_PROPGRANT, params);
						DBConnetionStateManager.addDbTask(data);
					}
				}
			} else {
				params = new Object[] { templetId, count, characterId, System.currentTimeMillis() };
				data = new SqlData(SqlDataIdFactory.createSqlId("Add_ORDER_PROPGANT", System.currentTimeMillis()), ADD_ORDER_PROPGRANT, params);
				DBConnetionStateManager.addDbTask(data);
			}
		} catch (SQLException e) {
			_log.error("���߷��͵���ʧ�� ����ɫId=" + characterId + "��ģ��ID=" + templetId + ",����=count", Config.SERVER_ID, e);
		} finally {
			if (ptmt != null) {
				ptmt.close();
			}
			if (con != null)
				con.close();
		}
	}

	/**
	 * �����߷��͵ĵ��߼��뵽��ɫ����
	 * 
	 * @param player
	 */
	public static void LoadCharacterProp(FuzePcInstance player) {
		if (!DBConnetionStateManager.getDbState() || player == null)
			return;
		ConnectionProxy con = null;
		PreparedStatementProxy ptmt = null;
		PreparedStatementProxy ptmt2 = null;
		ResultSet rs = null;
		Object[] params;
		SqlData data = null;
		int result = 0;
		int orderId = 0;
		int templetId;
		int count;
		try {
			con = ConnectionProxy.newInstance();
			if (con != null) {
				ptmt = con.prepareStatement(SELECT_ORDER_PROPGRANT);
				if (!DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, ptmt))
					return;
				ptmt.setLong(1, player.getObjectId());
				rs = ptmt.executeQuery();
				ptmt2 = con.prepareStatement(PHYSICAL_DELETE_PROPGRANT);
				while (rs.next()) {
					orderId = rs.getInt("orderId");
					templetId = rs.getInt("templetId");
					count = rs.getInt("count");
					if (!DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, ptmt2))
						return;
					if (player.getInventory().validateCapacityByItemId(templetId, count)) {
						player.addItem("���߷��͵ĵ��߼��뱳��", templetId, count, null, true);
						ptmt2.setInt(1, orderId);
						result = ptmt2.executeUpdate();
						if (result == PreparedStatementProxy.NETWORKDISCONNECTION) {
							params = new Object[] { orderId };
							data = new SqlData(SqlDataIdFactory.createSqlId("PHYSICAL_DELETE_PROPGRANT", orderId), PHYSICAL_DELETE_PROPGRANT, params);
							DBConnetionStateManager.addDbTask(data);
						}
					}
				}
			}
		} catch (SQLException e) {
			_log.error("ɾ���û����߶��� ����ID=" + orderId + " ʧ��", Config.SERVER_ID, e);
		} finally {
			if (ptmt2 != null)
				ptmt2.close();
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (ptmt != null) {
				ptmt.close();
			}
			if (con != null)
				con.close();
		}
	}
}
